// pages/i/score-charge.js
const scoreService = require('../../services/score.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userBalance: 0,
    selectedAmount: 0,
    customAmount: '',
    showCustomInput: false,
    presetAmounts: [0.01, 20, 50, 100, 300,500],
    loading: false,
    chargeId: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadUserBalance()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时重新加载余额
    this.loadUserBalance()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 加载用户云豆余额
   */
  async loadUserBalance() {
    try {
      const result = await scoreService.getBalance()
      if (result.success) {
        this.setData({
          userBalance: result.data.score || 0
        })
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载余额失败:', error)
      wx.showToast({
        title: '加载余额失败',
        icon: 'none'
      })
    }
  },

  /**
   * 选择预设金额
   */
  selectAmount(e) {
    const amount = e.currentTarget.dataset.amount
    this.setData({
      selectedAmount: amount,
      customAmount: '',
      showCustomInput: false
    })
  },

  /**
   * 选择自定义金额
   */
  selectCustom() {
    this.setData({
      selectedAmount: 0,
      customAmount: '',
      showCustomInput: true
    })
  },

  /**
   * 自定义金额输入
   */
  onCustomAmountInput(e) {
    this.setData({
      customAmount: e.detail.value
    })
  },

  /**
   * 发起充值
   */
  async startCharge() {
    const { selectedAmount, customAmount, showCustomInput } = this.data

    // 验证充值金额
    let chargeAmount = 0
    if (selectedAmount > 0) {
      chargeAmount = selectedAmount
    } else if (showCustomInput && customAmount) {
      const amount = parseFloat(customAmount)
      if (isNaN(amount) || amount < 10) {
        wx.showToast({
          title: '自定义金额不能低于10元',
          icon: 'none'
        })
        return
      }
      if (amount > 5000) {
        wx.showToast({
          title: '自定义金额不能超过5000元',
          icon: 'none'
        })
        return
      }
      chargeAmount = amount
    } else {
      wx.showToast({
        title: '请选择充值金额',
        icon: 'none'
      })
      return
    }

    this.setData({ loading: true })

    try {
      // 创建充值订单
      const chargeData = selectedAmount > 0 
        ? { amount: selectedAmount }
        : { custom_amount: chargeAmount }

      const result = await scoreService.createCharge(chargeData)
      
      if (result.success) {
        this.setData({
          chargeId: result.data.charge_id
        })

        // 发起微信支付
        await this.requestPayment(result.data)
      } else {
        wx.showToast({
          title: result.message,
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('充值失败:', error)
      wx.showToast({
        title: '充值失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  /**
   * 发起微信支付
   */
  async requestPayment(payData) {
    try {
      const result = await new Promise((resolve, reject) => {
        wx.requestPayment({
          timeStamp: payData.timeStamp,
          nonceStr: payData.nonceStr,
          package: payData.package,
          signType: payData.signType,
          paySign: payData.paySign,
          success: resolve,
          fail: reject
        })
      })

      // 支付成功
      wx.showToast({
        title: '充值成功',
        icon: 'success'
      })

      // 重新加载余额
      setTimeout(() => {
        this.loadUserBalance()
      }, 1000)

    } catch (error) {
      console.error('支付失败:', error)
      
      // 查询支付状态
      if (this.data.chargeId) {
        this.checkPaymentStatus()
      }
    }
  },

  /**
   * 检查支付状态
   */
  async checkPaymentStatus() {
    try {
      const result = await scoreService.queryChargeStatus(this.data.chargeId)
      if (result.success) {
        if (result.data.status === 1) {
          wx.showToast({
            title: '充值成功',
            icon: 'success'
          })
          this.loadUserBalance()
        } else {
          wx.showToast({
            title: '支付未完成',
            icon: 'none'
          })
        }
      }
    } catch (error) {
      console.error('查询支付状态失败:', error)
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadUserBalance().finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})